package com.itheima.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * WebSocket 主处理程序
 * 执行的是连接建立完了后的逻辑
 */
@Component
@Slf4j
public class MyWsHandler extends AbstractWebSocketHandler {

    private static Map<String , SessionBean> sessionBeanMap ;   //对传统的 session 做了个扩展
    private static AtomicInteger clientIdMaker ;    //Integer 的线程安全的类
    private static StringBuffer stringBuffer ;

    static {
        sessionBeanMap = new ConcurrentHashMap<>();
        clientIdMaker = new AtomicInteger(0);
        stringBuffer = new StringBuffer();
    }

    /**
     * 连接建立
     */
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        SessionBean sessionBean = new SessionBean(session, clientIdMaker.incrementAndGet());
        sessionBeanMap.put(session.getId() , sessionBean) ;
        log.info("{}：连接成功...", sessionBeanMap.get(session.getId()).getClientId());
        stringBuffer.append(sessionBeanMap.get(session.getId()).getClientId() +  "进入了群聊<br/>") ;
        this.sendMessage(sessionBeanMap);
    }


    /**
     * 收到消息
     */
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        log.info("{}：{}", sessionBeanMap.get(session.getId()).getClientId(), message.getPayload());
        this.sendMessage(sessionBeanMap);
    }


    /**
     * 传输异常
     */
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        if (session.isOpen()) {
            //如果会话还是开的
            session.close();
        }
        sessionBeanMap.remove(session.getId()); //删除这个会话
    }


    /**
     * 连接关闭
     */
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        sessionBeanMap.remove(session.getId());
        log.info("{}：关闭了连接...", sessionBeanMap.get(session.getId()).getClientId());
        this.sendMessage(sessionBeanMap);
    }

    /**
     * 每 2s 给客户端发送消息
     */
//    @Scheduled(fixedRate = 2000)
//    public void sendMessage() throws IOException {
//        for (String key : sessionBeanMap.keySet()) {
//            sessionBeanMap.get(key).getWebSocketSession().sendMessage(new TextMessage("心跳"));
//        }
//    }


    public void sendMessage(Map<String , SessionBean> sessionBeanMap) throws IOException {
        for (String key : sessionBeanMap.keySet()) {
            sessionBeanMap.get(key).getWebSocketSession().sendMessage(new TextMessage(stringBuffer.toString()));
        }
    }
}
